package cn.wzy.service.impl;

import cn.wzy.doc.CarDoc;
import cn.wzy.repository.CarDocRepository;
import cn.wzy.results.ResponseResult;
import cn.wzy.service.CarSearchService;
import cn.wzy.vo.CarSearchQuery;
import cn.wzy.vo.PageVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@ConditionalOnClass({ElasticsearchRestTemplate.class})
public class CarSearchServiceImpl implements CarSearchService {
   @Resource
    public CarDocRepository carDocRepository;
    @Resource
    private ElasticsearchRestTemplate elasticsearchTemplate;
    @Override
    public ResponseResult search(CarSearchQuery query) {
        // 构建本地查询器对象
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();

        // 1 高级查询
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        List<QueryBuilder> must = boolQuery.must();
        // 1.1 根据关键字查询  keyword  匹配标题 info 店铺名称 类型名称
        if(StringUtils.isNotBlank(query.getKeyword())){
            must.add(QueryBuilders.multiMatchQuery(query.getKeyword(),"title","carInfo","shopname","typeName"));
        }

        // 1.2 根据条件过滤
        // 根据类型id查询  typeId = 24
        if(Objects.nonNull(query.getTypeId())){
            must.add(QueryBuilders.termQuery("typeId", query.getTypeId()));
        }
        // 价格查询  3w-5w     3w<=costprice<5w
        if(Objects.nonNull(query.getPriceMin())){
            must.add(QueryBuilders.rangeQuery("costprice").gte(query.getPriceMin()));
        }
        if(Objects.nonNull(query.getPriceMax())){
            must.add(QueryBuilders.rangeQuery("costprice").lt(query.getPriceMax()));
        }
        // 车龄  reigstertime  carAge carAgeType
        // 举例:3年以上   今天2023-2-3  在2020-2-3以前   <2020-2-3
        // 3年以内  今天2023-2-3  在2020-2-3以后         >2020-2-3
        if(Objects.nonNull(query.getCarAge())){
            // 先计算出要对比的那个时间  now()-carAge
            Date date = DateUtils.addYears(new Date(), 0 - query.getCarAge());

            // 做区间查询
            if(query.getCarAgeType() == 0){
                must.add(QueryBuilders.rangeQuery("reigstertime").gt(date));
            }else{
                must.add(QueryBuilders.rangeQuery("reigstertime").lt(date));
            }
        }
//        其他判断条件

//        四个多选框条件
        if(Objects.nonNull(query.getCosteffective())){
            must.add(QueryBuilders.termQuery("costeffective", query.getCosteffective()));
        }
        if(Objects.nonNull(query.getRushsale())){
            must.add(QueryBuilders.termQuery("rushsale", query.getRushsale()));
        }
        if(Objects.nonNull(query.getQuasinewcar())){
            must.add(QueryBuilders.termQuery("quasinewcar", query.getQuasinewcar()));
        }
        if(Objects.nonNull(query.getTransitivecountry())){
            must.add(QueryBuilders.termQuery("transitivecountry", query.getTransitivecountry()));
        }

        queryBuilder.withQuery(boolQuery);

        // 2 排序
        String sortField = query.getSortField();
        // 如果sortField为null 怎么办?
        if(StringUtils.isBlank(sortField)){
            sortField = "onsaletime";
        }
        SortOrder sortOrder = SortOrder.DESC;
        if("asc".equals(query.getSortType())){
            sortOrder = SortOrder.ASC;
        }
        queryBuilder.withSort(SortBuilders.fieldSort(sortField).order(sortOrder));

        // 3 分页  第一个参数: 要查询的页数-1  第二个参数:每页显示条数
        queryBuilder.withPageable(PageRequest.of( query.getPageIndex().intValue()-1, query.getPageSize().intValue()));

        // 从es中查询数据
        // 使用ElasticsearchRestTemplate进行复杂查询
        SearchHits<CarDoc> searchHits = elasticsearchTemplate.search(queryBuilder.build(), CarDoc.class);
        if (searchHits.getTotalHits()>0){
            List<CarDoc> carDocList = searchHits.stream().map(SearchHit::getContent).collect(Collectors.toList());
            for (CarDoc row : carDocList) {
                String shopAddress = row.getShopAdress();
                if (StringUtils.isNotBlank(shopAddress))
                    row.setShopAdress(shopAddress.substring(0,shopAddress.indexOf("市")+1));
            }
            long total = searchHits.getTotalHits();

//        封装成PageVO返回
            PageVo pageVo = new PageVo();
            pageVo.setRows(carDocList);
            pageVo.setTotal(total);
            return ResponseResult.okResult(pageVo);
        }
        return ResponseResult.okResult(new PageVo());
    }
}
